using System;
using System.Data;
using System.Text;
using System.Windows.Forms;

using ctsu.BaseForms;
using ctsu.Data;

namespace ctsu.Admin.BusLogic
{
	public class SearchController : ISearchController
	{
		public event BusinessLogicEvents.BLSelectedItemEventHandler ItemSelected;
		protected FormSearchBase _form;
		protected SearchInfo _si;
		protected int _kCount = 0;

		public SearchController(FormSearchBase form, SearchInfo si)
		{
			this._form = form;  //the search form
			this._si = si;
			this._form.Text = this._si.Name + " Search";
			this._form.SearchFields.SelectedIndex = 0;
		}

		#region IFormClose implementation
		public void Apply(object sender, System.EventArgs e)
		{
			//
			ListView lvw = _form.SearchResults;
			if (lvw.Items.Count > 0)
			{
				if (lvw.SelectedItems.Count == 0)
				{
					MessageBox.Show(_form, "Select a row!", "Select Row",
						MessageBoxButtons.OK, MessageBoxIcon.Stop);
					return;
				}
				//this depends on the first column (id) being an int
				ListViewItem lvi = lvw.SelectedItems[0];
				_form.SelectedID = Convert.ToInt32(lvi.Text);

				BLReturnIDEventArgs args = new BLReturnIDEventArgs("", _form.SelectedID);
				if (ItemSelected != null)
					ItemSelected(this, args);
			}
			else
				_form.SelectedID = -1;
		}

		public void Accept(object sender, System.EventArgs e)
		{
			//
			ListView lvw = _form.SearchResults;
			if (lvw.Items.Count > 0)
			{
				if (lvw.SelectedItems.Count == 0)
				{
					MessageBox.Show(_form, "Select a row!", "Select Row",
						MessageBoxButtons.OK, MessageBoxIcon.Stop);
					return;
				}
				//this depends on the first column (id) being an int
				ListViewItem lvi = lvw.SelectedItems[0];
				_form.SelectedID = Convert.ToInt32(lvi.Text);

				BLReturnIDEventArgs args = new BLReturnIDEventArgs("", _form.SelectedID);
				if (ItemSelected != null)
					ItemSelected(this, args);

				_form.DialogResult = DialogResult.OK;

				_form.Close();
			}
			else
				_form.SelectedID = -1;
		}

		public void Cancel(object sender, System.EventArgs e)
		{

			_form.SelectedID = -1;
			_form.Close();
		}

		public void Exit(object sender, System.EventArgs e)
		{

		}

		public void Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{

		}
		#endregion IFormClose implementation

		#region ISearchController implementation
		public void SearchFieldsChanged(object sender, System.EventArgs e)
		{
		}

		public void GenericAction(object sender, System.EventArgs e)
		{
			this.Apply(sender, e);
		}

		public virtual void RunSearch(object sender, System.EventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			if (_form.SearchFields.SelectedIndex == -1)
			{
				MessageBox.Show(_form, "You must select a field to search by!", "Select Search By", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}
			string searchByField = ((ReportColumn)_form.SearchFields.SelectedItem).FieldName;

			StringBuilder sql = new StringBuilder("");

			if (this._si.SqlCommand.Length > 0)
				sql.Append(this._si.SqlCommand);
			else
			{
				sql.Append("SELECT ");
				//build select fields part
				foreach (ReportColumn rc in _si.SearchResultCols)
				{
					sql.Append(rc.FieldName + ",");
				}
				sql.Remove(sql.Length - 1, 1);
				sql.Append(" FROM " + _si.TableName);
			}

			string criteria = "";
			criteria = _form.Criteria.Text;

			//add there where for the select statement
			if (criteria.Length > 0)
			{
				//need schema info to build where part
				DataColumn dc = _si.TableSchema.Columns[searchByField];
				if (sql.ToString().IndexOf("WHERE") > -1)
					sql.Append(" AND " + searchByField);
				else
					sql.Append(" WHERE " + searchByField);

				if (dc.DataType == typeof(System.String))
				{
					sql.Append(" LIKE '" + criteria + "%'");
				}
				else if (dc.DataType == typeof(System.DateTime))
				{
					try
					{
						Convert.ToDateTime(criteria);
						sql.Append("='" + criteria + "'");
					}
					catch
					{
						sb.Append("Criteria is not a valid date.");
						MessageBox.Show(this._form, sb.ToString(), "Search Query Syntax Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
						return;
					}
				}
				else if (dc.DataType == typeof(System.Int32))
				{
					try
					{
						Convert.ToInt32(criteria);
						sql.Append("=" + criteria);
					}
					catch
					{
						sb.Append("Criteria is not a valid number.");
						MessageBox.Show(this._form, sb.ToString(), "Search Query Syntax Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
						return;
					}
				}
				else
					sql.Append("=" + criteria);
			}

			//add order by
			sql.Append(" ORDER BY " + searchByField);
			if (this._form.Descending.Checked)
				sql.Append(" DESC ");

			//clear the listview and fill with results
			_form.SearchResults.BeginUpdate();
			_form.SearchResults.Items.Clear();

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql.ToString());

				while (reader.Read())
				{
					ListViewItem lvi = new ListViewItem();
					int i = 0;
					string data;
					foreach (ReportColumn rc in _si.SearchResultCols)
					{
						if (reader.IsDBNull(i))
							data = "";
						else
							data = reader[rc.FieldName].ToString();
						if (i == 0)
							lvi.Text = data;
						else
							lvi.SubItems.Add(data);
						i++;
					}
					_form.SearchResults.Items.Add(lvi);
				}
				if (_form.SearchResults.Items.Count == 0)
					MessageBox.Show("No records were found.");

				if (_form.SearchResults.Items.Count == 1)
					this._form.SearchResults.Items[0].Selected = true;

				//resize the listview columns according to the results
				foreach (ColumnHeader ch in _form.SearchResults.Columns)
					ch.Width = -2;

			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Error in query syntax.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Search Query Syntax Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				_form.SearchResults.EndUpdate();
			}
		}
		#endregion ISearchController implementation




	}
}
